<?php
/**
 * Created by PhpStorm.
 * User: xh
 * Date: 2019/11/22
 * Time: 5:32 PM
 */

namespace app\model\weChat;



use think\Model;

class WeChatCode extends Model
{
    /** 获取二维码地址
     * 1.plat-member-Invite-info
     * @param string $url
     * @param string $codeKey
     * @param int $userId
     * @param string $identity
     * @param int $mold
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function regSite(&$url='',&$codeKey='',$userId=0,$identity='A',$mold=1){
        $map = ['user_id'=>$userId,'identity'=>$identity,'is_delete'=>0];
        $info = $this->where($map)->find();
        if(empty($info)){
            $site = '';
            $res = $this->reg($userId,$identity,$mold,$site,$codeKey);
            $url = ImageAddDomain($site);
            return $res;
        }else{
            $site = $info->code_site;
            $codeKey = $info->code_key;
            $url = ImageAddDomain($site);
            return true;
        }
    }

    /** 生成二维码
     * 1.model-weChat-WeChatCode-userGetSite 本类调用
     * @param int $userId
     * @param string $identity
     * @param int $mold
     * @param string $site
     * @param string $codeKey
     * @return bool
     */
    public function reg($userId=0,$identity='A',$mold=1,&$site='',&$codeKey=''){
        $codeKey = CreateScene();
        $buffer = WeChat('Serve')->codeUnLimit($codeKey,'pages/login/registered',$identity);
        if(empty($buffer)){return false;}
        $path = 'picture/we-chat/code-b';
        $res = ThirdParty('Picture')->saveBuffer($site,$buffer,$path);
        if(empty($res)){return false;}
        $this->code_site = $site;
        $this->code_key = $codeKey;
        $this->user_id = $userId;
        $this->is_use = empty($userId)?0:1;
        $this->identity = $identity;
        $this->mold = $mold;
        return $this->save();
    }

}